from itertools import chain

from django import forms
from django.utils.encoding import force_unicode
from django.template import loader, Context

#------------------------------------------------------------------------------


class SelectModelWidget(forms.TextInput):
    """
    @Usage: field = ModelChoiceField(queryset=Model.objects.all(),
                                    widget=SelectModelWidget(attrs={}))
    """

    def __init__(self, attrs=None, title=None,
                 template="widgets/select_widget.html"):
        super(SelectModelWidget, self).__init__(attrs)
        self.template = template
        self.title = title

    def render(self, name, value, attrs=None):
        if value is None: value = ''
        instance_text = ''
        options = []

        # Get the default queryset name as title if it isn't explicitly set
        if self.choices.queryset is not None and self.title is None:
            self.title = self.choices.queryset.model._meta.verbose_name.title()

        # Get the currently selected instance's text and remove the
        # blank select option from self.choices as we do not need it
        for key, text in self.choices:
            if key not in [None, '']:
                options.append((key, text))
                if key == value:
                    instance_text = text

        form_id = attrs.pop("id")
        widget_template = loader.get_template(self.template)
        context = Context({
                           "attrs": attrs,
                           "id": form_id,
                           "name": name,
                           "value": value,
                           "text": instance_text,
                           "title": self.title,
                           "options": options,
                          })

        return widget_template.render(context)

#------------------------------------------------------------------------------
